package z_multichat;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Vector;

public class MultiChatClientThread extends Thread {
	MultiChatClient mcc;
	Socket socket;
	boolean tFlag = true;
	ObjectOutputStream send;
	ObjectInputStream receive;
	String saveFolder = "/downloadClient/";
	byte[] data = new byte[10240];

	public MultiChatClientThread(MultiChatClient mcc, Socket s) {
		this.mcc = mcc;
		this.socket = s;
		File f = new File(saveFolder);
		if (!f.exists())
			f.mkdir();
	}

	public void run() {
		try {
			send = new ObjectOutputStream(socket.getOutputStream());
			receive = new ObjectInputStream(socket.getInputStream());

			SocketData sd = new SocketData("login", mcc.userID.getText(),
					" 님이 로그인하였습니다.", null);
			sendMsg(sd);

			while (tFlag) {
				sd = (SocketData) receive.readObject();
				mcc.dataSet(sd);

				if (sd.getCommand().equals("serverdown")) {
					tFlag = false;
					sendMsg(sd);

					// login을 전송한 후 서버는 userlist로 메시지를 재전송
				} else if (sd.getCommand().equals("userlist")) {
					mcc.list.removeAll();
					mcc.clientList = (Vector) sd.getObj();
					mcc.list.setListData(mcc.clientList);

				} else if (sd.getCommand().equals("logout")) {

					if (sd.getUser().equals(mcc.userID.getText())) {// 내자신이 로그아웃
						tFlag = false;
						mcc.clientList.removeAllElements();
					} else {
						mcc.clientList.removeElement(sd.getUser());
					}
					mcc.list.setListData(mcc.clientList);
				} else if (sd.getCommand().equals("fileTransPort")) {// 자신이 파일을 업로드하려 할때
					fileUploadServerConnect(sd);
				}else if(sd.getCommand().equals("fileserverconnect")){// 서버로 부터 파일을 다운로드하려 할때
					FileDownLoadClientThread fdct = new FileDownLoadClientThread(sd);
					fdct.join();
					fdct.start();
				}
			}

			receive.close();
			send.close();

			mcc.btnConnect.setEnabled(true);

			mcc.btnDisconnect.setEnabled(false);
			mcc.btnSend.setEnabled(false);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void sendMsg(SocketData sd) {
		try {
			int index = mcc.comboBox.getSelectedIndex();
			if (index > 0) {
				sd.setIndex(index);
			}

			send.writeObject(sd);
			send.flush();

			mcc.comboBox.setSelectedIndex(0);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void fileUploadServerConnect(SocketData sd) {
		String[] temp = ((String)sd.getObj()).split(",");
		String fileServerIP = temp[0];
		int fileServerPort = Integer.parseInt(temp[1]);
		mcc.dataSet(sd);
		FileUploadClient fc = new FileUploadClient(fileServerIP, fileServerPort);
		fc.setVisible(true);
	}


}
